import { privacyChannel } from './privacyChannel';
import { privacyChannelWeb } from './privacyChannelWeb';

export class privacyChannelVivo extends privacyChannelWeb {


    paraMap: Map<String, string> = new Map([
        ['bannerId', 'a18e66a53b254439832d1305da575520'],
        ['interId', 'a138d4c408ad4d29a6e8f8773001375d'],
        ['videoId', '89a1f7daf7fe4c95abc0974c63126fb7'],
        // ['htId', '1951116'],
        ['ctrlId', '67876d88c8946b1700d957c2'],
        // ['gid', '674546ecc5b6582182fb7e6a'],
    ]);


    ruanzhu: string = '著作权人:南京桔柚檬网络科技有限公司\n登记号:2021SR0614117';
    companyName: string = '南京桔柚檬网络科技有限公司';
    gameName: string = '最强大脑';


    exit(): void {
        this.channelObj.exitApplication();
    }

    getSysInfo() {

        if (!this.sysInfo) {
            try {
                this.sysInfo = this.channelObj.getSystemInfoSync();
            }

            catch {

            }
        }
        return this.sysInfo;
    }
    init() {
        const me = this;
        // 
        const ctrlId = me.getPara('ctrlId');
        console.error("===> init: ctrlId: ", ctrlId);
        if (ctrlId) {
            try {
                let query = me.channelObj.getLaunchOptionsSync().query;
                console.error("启动参数展示: ", JSON.stringify(query))
                if (query && query.path && query.path.indexof("key=fromid") >= 0) {
                    console.error("买量用户");
                    this.isBuyUser = true;
                } else {
                    console.error("不是买量用户");
                }
            }
            catch (e) {
                console.error("买量环境错误", JSON.stringify(e))
            }
            let reqData = null
            let sid = localStorage.getItem('__sid');
            if (!sid && me.channelObj && me.channelObj.getLaunchOptionsSync) {
                const lObj = me.channelObj.getLaunchOptionsSync();
                if (lObj && lObj.scene) {
                    sid = lObj.scene;
                    localStorage.setItem('__sid', sid);
                }
            }
            if (this.isBuyUser) {
                reqData = {
                    'id': ctrlId,
                    'fromid': 1,
                }
            } else {
                reqData = {
                    'id': ctrlId
                }
            }
            console.error("请求数据: jpost ");
            //const reqData = { 'id': ctrlId, sid };
            privacyChannel.jpost('https://ga.gametdd.com/adCtrl/agd/conf', reqData, (err, re) => {
                if (err) {
                    console.error("错误: ", err);
                    return;
                }
                if ('' + re.code !== '0') {
                    console.error('返回值错误:' + JSON.stringify(re));
                    return;
                }
                me.ctrl = re.data;
                console.error('====>返回', me.ctrl);
            });
        }
    }

    showVideo(succ, end = null) {
        if (cc.sys.platform == cc.sys.DESKTOP_BROWSER) {
            console.error("播放广告")
            succ();
            return
        }
        const id = this.getPara('videoId');
        if (!id) {
            return;
        }

        console.error('====>showVideo vivo');
        try {
            cc.game.pause();

            const rewardedAd = window['qg'].createRewardedVideoAd({
                posId: id,
            });
            rewardedAd.onError(err => {
                console.log("激励视频广告加载失败", err);
                cc.game.resume();
                privacyChannel.toast('暂无广告');
            });
            rewardedAd.onLoad(function (res) {
                console.log('激励视频广告加载完成-onload触发', JSON.stringify(res));
                rewardedAd.show().then(() => {
                    console.log('激励视频广告展示完成');
                }).catch((err) => {
                    console.log('激励视频广告展示失败', JSON.stringify(err));
                    cc.game.resume();
                    privacyChannel.toast('暂无广告');
                })
            })

            rewardedAd.onClose((res) => {
                cc.game.resume();
                end && end();
                console.log('视频广告关闭回调')
                if (res && res.isEnded) {
                    console.log("正常播放结束，可以下发游戏奖励");
                    succ();
                } else {
                    console.log("播放中途退出，不下发游戏奖励");
                }
            });

        } catch (e) {
            console.error('videoERR', e);
            cc.game.resume();
        }
    }

    private insertAD: any = null;

    doShowInter(id: string, isBanner: boolean = false, style?: any) {
        const height = (isBanner) ? cc.view.getVisibleSize().height / 2 - 100 : cc.view.getVisibleSize().height / 2 + 230;
        const conf = {
            posId: id,
            style: {
                top: height,
            }
        }

        if (style) {
            conf.style = style;
        }
        console.error("======>doshowInter", isBanner, height)
        if (this.insertAD) {
            //不能同时显示两个
            this.insertAD.destroy()
            console.error('原生板正在显示，不能重复显示', "已经删除");

        }
        const me = this;
        this.insertAD = me.channelObj.createCustomAd(conf);
        // me.insertAD.offHide();
        // me.insertAD.onHide(() => {
        //     console.error('原生板隐藏，删除原始板');
        //     me.insertAD.destroy();
        //     me.insertAD = null;
        //     // me.insertAD = me.channelObj.createCustomAd(conf);
        // });
        me.insertAD.offClose()
        me.insertAD.onClose(() => {
            console.error('原生板删除，删除原始板');
            me.insertAD.destroy();
            me.insertAD = null;
        })
        me.insertAD.offError();
        me.insertAD.onError(err => {
            console.error('原生模板广告加载失败' + JSON.stringify(err));
            me.insertAD = null;
        });
        me.insertAD.show().then(() => {
            console.log('原生模板广告展示完成');
        }).catch((err) => {
            console.log('原生模板广告展示失败' + JSON.stringify(err));
            me.insertAD = null;
        });
    }
    showUnqiueInter(isBanner: boolean = false, style?: any) {
        const id = this.getPara('interId');
        if (!id) {
            return;
        }
        // 插屏广告弹出页面
        // 在所有二级页面概率弹出
        // 0为关闭，1为开启
        // if (!this.getCtrl('p1')) {
        //     return;
        // }
        //控制所有二级页面插屏弹出的概率,单位为百分比
        // if (Math.random() > this.getCtrl('p2') / 100) {
        //     return;
        // }
        console.error('====>showInter');

        //原生插屏延迟
        const p14 = this.getCtrl('p14');
        const me = this;
        setTimeout(() => {
            try {
                me.doShowUniqueInter(id, isBanner, style);
            } catch {
                console.error("不是vivo")
            }

        }, p14 * 500);
    }
    showInter(isBanner: boolean = false, style?: any) {
        const id = this.getPara('interId');
        if (!id) {
            return;
        }
        // 插屏广告弹出页面
        // 在所有二级页面概率弹出
        // 0为关闭，1为开启
        // if (!this.getCtrl('p1')) {
        //     return;
        // }
        //控制所有二级页面插屏弹出的概率,单位为百分比
        // if (Math.random() > this.getCtrl('p2') / 100) {
        //     return;
        // }
        console.error('====>showInter');

        //原生插屏延迟
        const p14 = this.getCtrl('p14');
        const me = this;
        setTimeout(() => {
            try {
                me.doShowInter(id, isBanner, style);
            } catch {
                console.error("不是vivo")
            }

        }, p14 * 500);
    }

    doShowUniqueInter(id: string, isBanner: boolean = false, style?: any) {
        const height = (isBanner) ? cc.view.getVisibleSize().height / 2 : cc.view.getVisibleSize().height / 2 + 230;
        const conf = {
            posId: id,
            style: {
                top: height,
            }
        }
        if (style) {
            conf.style = style;
        }
        if (this.insertAD) {
            //不能同时显示两个
            console.error('原生板正在显示，不能重复显示');
            return;
        }
        const me = this;
        this.insertAD = me.channelObj.createCustomAd(conf);
        // me.insertAD.offHide();
        // me.insertAD.onHide(() => {
        //     console.error('原生板隐藏，删除原始板');
        //     cc.resources.load("kuangDian/kuangDian", cc.Prefab, (error, assert: cc.Prefab) => {
        //         if (error) {
        //             console.error(error);
        //             return;
        //         }
        //         let node = cc.instantiate(assert);
        //         cc.director.getScene().getChildByName('Canvas').getChildByName("UI").addChild(node);
        //     });
        //     me.insertAD.destroy();
        //     me.insertAD = null;
        //     // me.insertAD = me.channelObj.createCustomAd(conf);
        // });
        me.insertAD.offClose()
        me.insertAD.onClose(() => {
            console.error('原生板删除，删除原始板');
            cc.resources.load("kuangDian/kuangDian", cc.Prefab, (error, assert: cc.Prefab) => {
                if (error) {
                    console.error(error);
                    return;
                }
                let node = cc.instantiate(assert);
                cc.director.getScene().getChildByName('Canvas').getChildByName("UI").addChild(node);
            });
            me.insertAD.destroy();
            me.insertAD = null;
        })
        me.insertAD.offError();
        me.insertAD.onError(err => {
            console.error('原生模板广告加载失败' + JSON.stringify(err));
            me.insertAD = null;
        });
        me.insertAD.show().then(() => {
            console.log('原生模板广告展示完成');
        }).catch((err) => {
            console.log('原生模板广告展示失败' + JSON.stringify(err));
            me.insertAD = null;
        });
    }

    showStyleInter(id: number) {
        console.error("===>showStyleInter");
        let style = {
            top: this.getSysInfo().windowHeight / 2 + 200
        };
        this.showInter(false, style);
    }


    closeInter() {

        console.error('====>closeInter');
        if (this.insertAD) {
            this.insertAD.destroy();
        }
    }

    showBanner() {
        const id = this.getPara('bannerId');
        if (!id) {
            return;
        }
        console.error('====>showBanner');
        const bannerAd = this.channelObj.createBannerAd({ 'posId': id });
        bannerAd.onError(err => {
            console.log('banner广告加载失败' + JSON.stringify(err));
        });
        bannerAd.show().then(() => {
            console.log('banner广告展示完成');
        }).catch((err) => {
            console.log('banner广告展示失败' + JSON.stringify(err));
        });
        bannerAd.onHide(() => {
            console.log('banner广告隐藏');
        });
    }

    showHt() {

    }
    button = null
    button1 = null
    createShortcutButton() {
        const me = this;

        me.button = me.channelObj.createShortcutButton({
            type: 'image',
            style: {
                left: this.getSysInfo().screenWidth - 28 - 100,
                top: 750,
                width: 100,
                height: 100
            }
        })

        var startHandler = function (data) {
            console.log(data)
            me.button.hide()
            me.button1.hide()
        };
        me.button.onTap(startHandler)

    }


    createShortcutButtonResistance() {
        const me = this;
        me.button1 = me.channelObj.createShortcutButton({
            type: 'image',
            image: "assets/texture/sideBar/logo.png",
            style: {
                left: this.getSysInfo().screenWidth - 28 - 100,
                top: 100,
                width: 50,
                height: 50
            }
        })

        var startHandler = function (data) {
            console.log(data)
            me.button1.hide()
            me.button.hide()
        };
        me.button1.onTap(startHandler)

    }
    showButton() {
        if (cc.sys.platform == cc.sys.DESKTOP_BROWSER) {
            return
        }
        this.button.show()
    }
    hideButton() {
        if (cc.sys.platform == cc.sys.DESKTOP_BROWSER) {
            return
        }
        this.button.hide()
    }

    hasShortcutInstalled(end) {
        if (cc.sys.platform == cc.sys.DESKTOP_BROWSER) {
            return
        }
        const me = this;
        me.channelObj.hasShortcutInstalled({
            success: function (status) {
                if (status) {
                    end && end(true)
                    console.log('已创建')
                } else {
                    end && end(false)
                    console.log('未创建')
                }
            }
        })

    }

    installShortcut() {
        if (cc.sys.platform == cc.sys.DESKTOP_BROWSER) {
            return
        }
        const me = this;
        me.channelObj.installShortcut({
            success: function () {
                console.log('创建成功')
                me.button1.hide()
                me.button.hide()
            }
        })

    }

}